package br.com.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.com.bean.EngineBean;
import br.com.business.EngineBusiness;

@WebServlet(value="/EngineServlet")
public class EngineServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		String endpoint = "http://dbpedia.org/sparql";
		if (!"".equals(request.getParameter("endpoint"))) {
			endpoint = request.getParameter("endpoint");
		}
		String extend = request.getParameter("extend");
		if(!"on".equals(extend)) extend = "";
		String query = request.getParameter("query");
		
		EngineBusiness engineBusiness = new EngineBusiness();
		EngineBean<String> bean = engineBusiness.getUriByLabel2(endpoint, query, extend);
		
		String uri = bean.getValues("uri").get(0);
		
		bean = engineBusiness.getPropertiesByUri2(endpoint, uri);
		
		EngineBean<String> values = new EngineBean<String>();
		for(String property : bean.getValues("predicate")) {
			EngineBean<String> bla = engineBusiness.getObjectByUriAndProperty2(endpoint, uri, property);
			System.out.println(bla);
			values.append(bla);
		}
		
		if (!"".equals(values.toString())) request.setAttribute("resultado", values.toString());
		else request.setAttribute("resultado", "Erro ao carregar uri");
		
		request.setAttribute("endpoint", endpoint);
		request.setAttribute("query", query);
		request.setAttribute("extend", extend);
		
		request.getRequestDispatcher("./resultado.jsp").forward(request, response);
	}
}
